package com.example.ByteStream;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;
import java.util.Set;

/**
 * @author Jason
 * @PACKAGE_NAME com.example.ByteStream
 * @Description Properties集合
 * @date 2023-12-13 18:18
 */
public class PropertiesDemo {
    public static void main(String[] args) throws IOException {
        //1.创建集合
        Properties properties = new Properties();
        //2.添加元素
        properties.setProperty("username", "Jason");
        properties.setProperty("age", "20");
        //3.获取元素
        System.out.println(properties.toString());
        //4.遍历集合
        //4.1keySet
        System.out.println("-----keySet-----");
        for (Object key : properties.keySet()) {
            System.out.println(key);
        }
        System.out.println("-----keySet-----");

        //4.2entrySet
        System.out.println("-----entrySet-----");
        for (Object key : properties.entrySet()) {
            System.out.println(key);
        }
        System.out.println("-----entrySet-----");
        //4.3stringPropertyNames
        System.out.println("-----stringPropertyNames-----");
        Set<String> strings = properties.stringPropertyNames();
        for (String string : strings) {
            System.out.println(string + "->" + properties.getProperty(string));
        }
        System.out.println("-----stringPropertyNames-----");

        //5流相关
        //5.1list方法打印文件到指定文件
        PrintWriter pw = new PrintWriter("d:\\print.txt");
        properties.list(pw);
        pw.close();
        //5.2store方法 保存
        FileOutputStream fos = new FileOutputStream("d:\\store.properties");
        properties.store(fos, "这是注释");
        fos.close();
        //5.3load方法 加载
        Properties properties1 = new Properties();
        FileInputStream fis = new FileInputStream("d:\\store.properties");
        properties1.load(fis);
        fis.close();
        System.out.println(properties1.toString());
    }
}
